package com.easy.carl.algorithm.StackAndQueue;

import java.util.*;

/**
 * @ClassName TopKFrequent347
 * @Description TODO
 * @Author zheng
 * @Date 2021/12/31 14:48
 * @Version 1.0
 **/
public class TopKFrequent347 {
    public int[] topKFrequent(int[] nums, int k) {
        Map<Integer, Integer> hashMap = new HashMap<Integer, Integer>();
        for (int num : nums) {
            hashMap.put(num, hashMap.getOrDefault(num, 0) + 1);
        }
        PriorityQueue<Map.Entry<Integer, Integer>> queue = new PriorityQueue<>(((o1, o2) -> o2.getValue() - o1.getValue()));
        queue.addAll(hashMap.entrySet());
        k = Math.min(k, queue.size());
        int[] res = new int[k];
        while (!queue.isEmpty() && k > 0) {
            res[--k] = queue.poll().getKey();
        }
        return res;
    }

    public static void main(String[] args) {
        TopKFrequent347 topKFrequent347 = new TopKFrequent347();
        System.out.println(Arrays.toString(topKFrequent347.topKFrequent(new int[]{1, 1, 1}, 2)));
    }
}
